<?php

namespace App\Containers\AppSection\Data\Actions;

use App\Containers\AppSection\Confirmation\Tasks\DeleteAllConfirmsByValueTask;
use App\Containers\AppSection\Confirmation\Tasks\FindConfirmationByCodeTask;
use App\Containers\AppSection\Data\Tasks\UpdatePersonalTask;
use App\Containers\AppSection\Data\UI\API\Requests\UpdatePersonalRequest;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\ChangeProfilePhoneTask;
use App\Containers\AppSection\Profile\Tasks\UpdateProfileTask;
use App\Ship\Parents\Actions\Action;

class UpdatePersonalAction extends Action
{
    public function run(UpdatePersonalRequest $request)
    {
        //Валидация кода, отправленного на телефон
        if (!empty($request->getInputByKey('phone_code'))) {
            //Поиск кода
            app(FindConfirmationByCodeTask::class)->run(
                $request->getInputByKey('phone_code'), $request->getInputByKey('phone'),
                config('appSection-confirmation.confirms.phone.requests.register'),
                config('appSection-confirmation.confirms.phone.type')
            );

            //Смена телефона
            app(ChangeProfilePhoneTask::class)->run($request->profile()->id, $request->getInputByKey('phone'));
        }

        $data = $request->sanitizeInput([
            'fio',
            'without_patronymic',
            'birth_date',
            'ogrnip',
            'position',
            'inn',
            'snils',
            'birth_place',
            'registration_address',
            'address_matches',
            'residence_address',
        ]);

        //Обновление персональных данных
        $personal = app(UpdatePersonalTask::class)->run($request->profile()->legal_form->personal->id, $data);

        //Смена статуса аккредитации
        if (!$request->profile()->hasAccreditationStatus('accreditation_returned'))
            app(UpdateProfileTask::class)
                ->run($request->profile()->id, [
                    'accreditation_status_key' => 'accreditation_not_accredited',
                    'accredited_at' => null
                ]);


        //Удаление отправленных кодов на телефон
        app(DeleteAllConfirmsByValueTask::class)
            ->run($request->getInputByKey('phone'), config('appSection-confirmation.confirms.phone.requests.register'), config('appSection-confirmation.confirms.phone.type'));


        app(CreateLogTask::class)->run($request->profile()->id, 'Редактирование персональных данных', 'profile');

        return $personal;
    }
}
